package com.lee.taste.spider.sohu.spider;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.dom4j.Element;

import com.lee.taste.spider.HttpRequest;
import com.lee.taste.spider.sohu.db.BrandDao;
import com.lee.taste.spider.sohu.entity.Model;
import com.lee.taste.spider.sohu.entity.SaleModel;
import com.lee.taste.spider.sohu.xml.XMLParase;
import com.lee.taste.spider.sohu.xml.XMLUtils;
public class ModelSpider {

	private static BrandDao brandDao = new BrandDao();
	private static final String TYPE_CORP = "corp";
	public static List<Model> crawl(String url) throws Exception  {
		String xml = HttpRequest.sendGet(url, "");
		List<Model> list = parseModel(XMLParase.parseXml(xml));  
		brandDao.batchUpdateModel(list);
		return list;
	}
	private static List<Model>  parseModel(Element element){
		List<Model> list = Lists.newArrayList();
		if(element == null){
			return list;
		}
		List<Element> elesBrand = element.elements("model");
		String corpName = "";
		for(Element e : elesBrand){
			String type = XMLUtils.getAttributeValue(e,"type");
			if(StringUtils.equalsIgnoreCase(type, TYPE_CORP)){
				corpName = XMLUtils.getAttributeValue(e,"name");
			}else{
				Model brand = new Model(XMLUtils.getAttributeValue(e,"id"),XMLUtils.getAttributeValue(e,"name"),XMLUtils.getAttributeValue(element,"id"),
						"",corpName);
				list.add(brand);
			}
		}
		return list;
	}
	
	public static void crawlSales(String url ) throws Exception  {
		String xml = HttpRequest.sendGet(url, "");
		List<SaleModel> list = parseSales(XMLParase.parseXml(xml));  
		brandDao.batchUpdateModelSales(list);
	}
	private static List<SaleModel>  parseSales(Element element){
		List<SaleModel> list = Lists.newArrayList();
		if(element == null){
			return list;
		}
		List<Element> elesBrand = element.elements("sales");
		for(Element e : elesBrand){
			SaleModel entity = new SaleModel(XMLUtils.getAttributeValue( element,"id"),XMLUtils.getAttributeValue( element,"name")
					,XMLUtils.getAttributeValue(e,"date"),XMLUtils.getAttributeValue(e,"salesNum"));
			list.add(entity);
			System.out.println(entity.toString());
		}
		return list;
	}
}
